<template>
	<!-- v-if="showPriceTable" -->
	<div style="" class="price-table">
		<!-- 属性添加框 handleForm->(attrWrapper->attrInput)+spanCom  -->
		<handle-table
			ref="handleTable"
			@setUnit="setUnit"
			@switchChecked="switchChecked"
			@handleOk="handleTableChange"
			@getTotalData="getTotalData"
			@renderData="renderData"
			@renderPriceTableData="renderPriceTableData"
		></handle-table>
		<!-- 定价表 -->
		<a-layout>
			<a-layout-content style="background: #fff">
				<a-page-header>
					<template slot="extra">
						<!-- <a-button type="primary" @click="addAttr">
							<a-icon type="file-add" />
							添加
						</a-button> -->

						<a-button type="primary" @click="backPrice">
							<a-icon type="left" />
							返回
						</a-button>
					</template>
					<template slot="title">
						{{ `定价表 ` }}
						<span
							style="font-size: 14px; font-weight: 400; margin-left: 10px"
							>{{ `sku总数: ${pagination.total}` }}</span
						>
					</template>
				</a-page-header>

				<a-table
					v-if="flag"
					:columns="columns"
					:data-source="data"
					:pagination="pagination"
					@change="handleTableChange"
					:rowKey="
						(record, index) => {
							return index
						}
					"
				>
					<!-- 自定义表头内容 -->
					<!-- <span slot="定价_title" style="white-space: nowrap">定价</span> -->
					<!-- 自定义单元格列的内容 -->
					<!-- <span
						slot="定价_content"
						style="white-space: nowrap"
						slot-scope="text, record"
						>{{ record["定价"] ? record["定价"] / 100 : "" }}</span
					> -->

					<template slot="定价" slot-scope="text, record">
						<!-- :text="text" -->
						<editable-cell
							v-has="'market.createPrice'"
							:text="record['定价']"
							@change="onCellChange(record, '定价', $event)"
						/>
					</template>

					<span slot="section" slot-scope="text, record">
						{{
							record.section
								? record.section.split(",")[0] +
								  `${unit ? unit : "件"}-` +
								  record.section
										.split(",")[1]
										.substr(0, record.section.split(",")[1].lastIndexOf("]")) +
								  `${unit ? unit : "件"}` +
								  "]"
								: ""
						}}
					</span>

					<!-- <a slot="name" slot-scope="text">{{ text }}</a> -->
					<!-- <span slot="customTitle"><a-icon type="smile-o" /> Name</span> -->
					<!-- <span slot="tags" slot-scope="tags">
						<a-tag
							v-for="tag in tags"
							:key="tag"
							:color="
								tag === 'loser'
									? 'volcano'
									: tag.length > 5
									? 'geekblue'
									: 'green'
							"
						>
							{{ tag.toUpperCase() }}
						</a-tag>
					</span> -->
				</a-table>
			</a-layout-content>
		</a-layout>

		<a-button
			v-has="'market.update'"
			@click="submitTotalAttrs"
			class="submit-btn"
			style=""
			size="default"
			type="primary"
			>提交</a-button
		>
	</div>
</template>
<script>
	const EditableCell = {
		template: `
																	<div class="editable-cell">
																	<div v-if="editable" class="editable-cell-input-wrapper">
																	<a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
																	type="check"
																	class="editable-cell-icon-check"
																	@click="check"
																	/>
																	</div>
																	<div v-else class="editable-cell-text-wrapper">
																	{{ value ? value : '' }}
																	<a-icon type="edit" class="editable-cell-icon" @click="edit" />
																	</div>
																	</div>
																	`,
		props: {
			text: [String, Number, Boolean],
		},
		data() {
			return {
				value: this.text,
				editable: false,
			}
		},
		methods: {
			handleChange(e) {
				const value = e.target.value
				this.value = value
			},
			check() {
				this.editable = false
				this.$emit("change", this.value)
			},
			edit() {
				this.editable = true
			},
		},
	}
	// ======================================================================
	const columns = [
		// {
		// 	title: "SKU编号",
		// 	dataIndex: "skuId",
		// 	key: "skuId",
		// 	// slots: { title: "customTitle" },
		// 	// scopedSlots: { customRender: "name" },
		// },
		// {
		// 	title: "属性1",
		// 	dataIndex: "age",
		// 	key: "age",
		// },
		// {
		// 	title: "属性2",
		// 	dataIndex: "address",
		// 	key: "address",
		// },
		// {
		// 	title: "属性3",
		// 	key: "tags",
		// 	dataIndex: "tags",
		// },
		// {
		// 	title: "定价",
		// 	key: "tags2",
		// 	dataIndex: "tags2",
		// },
	]

	const data = [
		// {
		// 	// key: "1",
		// 	skuId: "001-100-101203305",
		// 	// age: 32,
		// 	// address: "数据",
		// 	// tags: ["nice", "developer"],
		// },
		// {
		// 	key: "2",
		// 	name: "徐先生",
		// 	age: 42,
		// 	address: "数据",
		// 	tags: ["loser"],
		// },
		// {
		// 	key: "3",
		// 	name: "徐先生",
		// 	age: 32,
		// 	address: "数据",
		// 	tags: ["cool", "teacher"],
		// },
	]
	import handleTable from "./handleForm.vue"
	import marketHttp from "@/api/market"
	import { mapGetters, mapMutations } from "vuex"
	const lodash = require("lodash")
	export default {
		props: {},
		data() {
			return {
				pagination: {
					current: 1,
					pageSize: 20,
					total: 0,
					totalPage: 0,
					showSizeChanger: true,
					showTotal: (total) => `总 ${total} 条`,
				},
				data,
				columns,
				option3: {},
				text: "",
				flag: true, // 控制价格表显示隐藏
				mulFlag: true, // 刚获取数据时 只要修改了价格操作 原价格统一 * 100
				changePFlag: false, // 价格是否修改过标志
				unit: "",
				// checked: false,
			}
		},
		computed: {
			...mapGetters({
				ProductDetail: "getProductDetail",
				getMarketId: "getMarketId",
				getPtype: "getPtype",
				// getProductId: "getProductId",
				// showPriceTable: "getPriceTableStatus",
				autoOn: "getAutoOn",
			}),
		},
		// watch: {
		// 	showPriceTable(a, b) {
		// 		console.log(a, b)
		// 		if (a === true) {
		// 			this.data = []

		// 			// 点击编辑 SKU时 一进来 就获取产品详情
		// 			this.getProductDetail_()
		// 		}
		// 	},
		// },
		created() {
			this.getProductDetail_()
		},
		methods: {
			setUnit(unit) {
				console.log(unit)
				this.unit = unit
			},
			submitTotalAttrs() {
				this.$refs.handleTable.submitAttrs()
			},
			addBatchSet() {
				if (this.columns) {
					if (
						!this.columns.some((item) => {
							return item.key === "section"
						})
					) {
						this.columns.splice(this.columns.length, 0, {
							title: `批量设定${this.unit ? `(${this.unit})` : "(件)"}`,
							// key: "section",
							// dataIndex: "section",
							scopedSlots: { customRender: "section" },
						})
					}
				}
			},
			removeBatchSet() {
				let index =
					this.columns &&
					this.columns.findIndex((item) => {
						return item.key === "section"
					})
				console.log(index)
				this.columns.splice(index, 1)
			},
			...mapMutations({
				// setPriceTableStatus: "setPriceTableStatus",
				setProductDetail: "setProductDetail",
				setAutoOn: "setAutoOn",
			}),
			async getProductDetail_() {
				await marketHttp
					// .select(this.getProductId, "/skuproduct")
					.select(this.$route.params.id, "/skuproduct")
					.then((response) => {
						console.log("产品详情", response)
						if (response.code !== 1) {
							this.$message.error(response.message)
							return
						}

						this.$message.success(response.message)

						this.mulFlag = true // 实现数据 乘以 一次 100
						for (let key in response.data) {
							if (["option1", "option2", "option3"].includes(key)) {
								response.data[key] = response.data[key]
									? JSON.parse(response.data[key])
									: ""
							}
						}

						if (response.data.option3) {
							if (
								response.data.option3.values &&
								response.data.option3.values.length > 0
							) {
								response.data.option3.values.map((item) => {
									item["定价"] = item["定价"] ? item["定价"] : ""
								})
							}
						}

						console.log(response.data["option3"])

						this.pagination.total = response.data["option3"]
							? response.data["option3"].values.length
							: 0

						this.pagination = { ...this.pagination }

						console.log("产品详情", response)
						// if (Object.keys(response.data.option2).length > 0) {
						// 	this.setAutoOn(true)
						// }
						this.setProductDetail({ ...response.data })

						return
					})
					.catch((e) => {
						console.log(e)
					})
			},
			// search() {
			// 	this.data = []
			// 	this.pagination.current = 1
			// 	this.getData()
			// },
			changePrice(data, record, value) {
				// 多次修改价格 这块代码只能执行一次
				if (this.mulFlag) {
					data.forEach((item) => {
						item["定价"] = item["定价"] ? Math.round(item["定价"] * 100) : ""
					})
					this.mulFlag = false
				}

				// ============================否则 只要修改的那一条数据价格 * 100================
				let index = data.findIndex((item) => {
					return item["id"] === record["id"]
				})
				data[index]["定价"] = Math.round(value * 100)
				return data
				// return data.map((item) => {

				// 			item["价格"] = item["价格"] ? item["价格"] * 100 : ""
				// 			return item
				// 		})
			},
			// 修改价格
			onCellChange(record, dataIndex, value) {
				this.changePFlag = true
				console.log(this.option3)
				console.log(this.data)
				console.log(record, dataIndex, value)
				// record[dataIndex] = value * 100 // 化成分

				// =================删除一条属性保存后SKU编码会改变  与网络返回数据SKU不一致 需要前端去主动生成唯一ID==================
				// let index = this.option3.values.findIndex((item) => {
				// 	return item["id"] === record["id"]
				// })
				// console.log(index)
				// this.option3.values[index]["定价"] = value * 100
				// console.log(this.option3)
				// ==================================================
				// let index = this.data.findIndex((item) => {
				// 	return item["id"] === record["id"]
				// })
				// console.log(index)
				// this.data[index]["定价"] = value * 100
				// console.log(this.data)
				// ===================================
				// let handleTable = this.$refs["handleTable"]
				let params = {
					market_id: this.getMarketId,
					ptype: parseFloat(this.getPtype),
					sku_code: record["SKU"],
					price: Math.round(value * 100), // 化成分
					// option1: handleTable.option1.map((item) => {
					// 	return {
					// 		name: item.name,
					// 		code: item.code,
					// 		unit: item.unit || "",
					// 		val: parseFloat(record[item.name]) || record[item.name],
					// 	}
					// }),

					// option2: handleTable.option2,

					// option3: JSON.stringify(this.option3),
					option3: JSON.stringify({
						titles: this.option3.titles,
						values: this.changePrice(this.data, record, value),
					}),
				}

				// 产品添加SKU报价表
				marketHttp
					.createPrice(params, "/skupricelist")
					.then((response) => {
						console.log(response)
						if (response.code !== 1) {
							this.$message.error(response.message)
							return
						}
						this.$message.success("价格修改成功")
						return
					})
					.catch((e) => {
						console.log(e)
					})
				console.log(params)

				// const dataSource = [...this.dataSource]
				// const target = dataSource.find((item) => item.key === key)
				// if (target) {
				// 	target[dataIndex] = value
				// 	this.dataSource = dataSource
				// }
			},
			//  点击编辑、提交时 网络请求回来的数据
			handleTitles_2(totalData) {
				console.log({ ...totalData })
				if (totalData.titles && totalData.titles.length > 0) {
					if (
						!totalData.titles.some((item) => {
							return Object.values(item).includes("SKU")
						})
					) {
						totalData.titles.splice(0, 0, {
							title: "SKU",
							dataIndex: "SKU",
							key: "SKU",
						})
					}
					console.log(
						!totalData.titles.some((item) => {
							return (
								item["scopedSlots"] &&
								item["scopedSlots"]["customRender"] === "section"
							)
						})
					)
					if (
						!totalData.titles.some((item) => {
							return (
								item["scopedSlots"] &&
								item["scopedSlots"]["customRender"] === "section"
							)
						})
					) {
						// 插入到最后一项
						var tempTitles = [...JSON.parse(JSON.stringify(totalData.titles))]
						tempTitles.splice(totalData.titles.length, 0, {
							title: `批量设定${this.unit ? `(${this.unit})` : "(件)"}`,
							// dataIndex: "section",
							// key: "section",
							scopedSlots: { customRender: "section" },
						})
					} else {
						// var tempTitles = [...totalData.titles]
						var tempTitles = [...JSON.parse(JSON.stringify(totalData.titles))]
						for (let i = 0, len = tempTitles.length; i < len; i++) {
							if (
								tempTitles[i]["scopedSlots"] &&
								tempTitles[i]["scopedSlots"]["customRender"] === "section"
							) {
								tempTitles[i]["title"] =
									tempTitles[i]["title"] + `(${this.unit ? this.unit : "件"})`
							}
						}
					}

					// this.columns = totalData.titles
					this.columns = tempTitles

					if (this.autoOn === false) {
						let index = this.columns.findIndex((item) => {
							return item["key"] === "section"
						})
						this.columns.splice(index, 1)
					}

					if (
						!this.columns.some((item) => {
							return item["key"] === "定价"
						})
					) {
						if (this.autoOn === true) {
							this.columns.splice(this.columns.length - 1, 0, {
								dataIndex: "定价",
								key: "定价",
								scopedSlots: {
									customRender: "定价",
								},
								title: "单件定价(元)",
							})
						} else {
							this.columns.splice(this.columns.length, 0, {
								dataIndex: "定价",
								key: "定价",
								scopedSlots: {
									customRender: "定价",
								},
								title: "单件定价(元)",
							})
						}
					}
					console.log(441, this.columns)
				} else if (totalData.values && totalData.values.length > 0) {
					this.columns = []
					// for (let i = 0, len = totalData.values.length; i < len; i++) {
					this.columns.push({
						title: "SKU",
						dataIndex: "SKU",
						key: "SKU",
					})
					totalData.values[0] = lodash.omit(totalData.values[0], [
						"定价",
						"section",
						"SKU",
					])
					for (let key in totalData.values[0]) {
						this.columns.push({
							title: key,
							dataIndex: key,
							key: key,
						})
					}

					this.columns.push({
						title: "单件定价(元)",
						dataIndex: "定价",
						key: "定价",
						scopedSlots: {
							customRender: "定价",
						},
					})

					if (this.autoOn === true) {
						this.columns.push({
							title: `批量设定${this.unit ? `(${this.unit})` : "(件)"}`,
							// dataIndex: "section",
							// key: "section",
							scopedSlots: { customRender: "section" },
						})
					}

					if (this.autoOn === false) {
						let index = this.columns.findIndex((item) => {
							return item["key"] === "section"
						})
						this.columns.splice(index, 1)
					}

					// }
					console.log(this.columns)

					// = totalData.values.map(item => {

					// })
				}
			},
			//  点击编辑、提交时 网络请求回来的数据
			renderData(totalData) {
				console.log(totalData)
				if (!totalData) {
					return
				}

				// {
				// 	title: "SKU编号",
				// 	dataIndex: "skuId",
				// 	key: "skuId",
				// 	// slots: { title: "customTitle" },
				// 	// scopedSlots: { customRender: "name" },
				// }
				this.handleTitles_2(totalData)
				// 页面表格显示的数据
				this.data = totalData.values
				// this.columns = totalData.titles
				console.log(this.data)

				// 重新渲染定价表 修复提交后 价格不更新问题
				this.flag = false
				setTimeout(() => {
					this.flag = true
				})

				// this.option3 = totalData

				// let totalData = { ...totalData }
				// 深度拷贝
				let values_ = JSON.parse(JSON.stringify(totalData.values))
				// let values_ = [...totalData.values]
				console.log(values_)
				// 处理 即将提交到后端数据 价格 * 100
				this.option3 = {
					titles: totalData.titles,
					values: values_.map((item) => {
						item["定价"] = item["定价"] ? Math.round(item["定价"] * 100) : ""
						return item
					}),
				}
				console.log(this.option3)
			},
			// 点击保存时渲染页面
			renderPriceTableData(totalData) {
				// 页面展示
				console.table({
					columns: this.columns,
					data: this.data,
					totalData: totalData,
				})
				// 实现给一个属性添加赋值后  原价格不变 以 totalData 为准
				// let tempData = []
				for (let i = 0, len = totalData.values.length; i < len; i++) {
					for (let j = 0, lenJ = this.data.length; j < lenJ; j++) {
						if (totalData.values[i]["SKU"] === this.data[j]["SKU"]) {
							totalData.values[i]["定价"] = this.data[j]["定价"]
						}
					}
				}
				this.columns = totalData.titles
				this.data = totalData.values
				// this.data = tempData
				// 重新渲染定价表 修复提交后 价格不更新问题
				this.flag = false
				setTimeout(() => {
					this.flag = true
					this.pagination.total = this.data.length
					console.log(this.autoOn)
					if (this.autoOn) {
						this.addBatchSet()
					} else {
						// 此时属于关闭批量设定状态 价格字段属于最后一位
						this.columns &&
							this.columns.push({
								title: "单件定价(元)",
								dataIndex: "定价",
								key: "定价",
								scopedSlots: {
									customRender: "定价",
								},
							})
						this.removeBatchSet()
					}
				})
			},
			handleTitles_1(totalData, data = []) {
				data = JSON.parse(JSON.stringify(data))
				console.log(totalData, data)
				let tempTitles = []
				if (totalData.titles && totalData.titles.length > 0) {
					// if (
					// 	!totalData.titles.some((item) => {
					// 		return Object.values(item).includes("SKU")
					// 	})
					// ) {
					// 	tempTitles.splice(0, 0, {
					// 		title: "SKU",
					// 		dataIndex: "SKU",
					// 		key: "SKU",
					// 	})
					// }

					// if (
					// 	!totalData.titles.some((item) => {
					// 		return Object.values(item).includes("section")
					// 	})
					// ) {
					// 	tempTitles.splice(totalData.titles.length, 0, {
					// 		title: "批量设定",
					// 		dataIndex: "section",
					// 		key: "section",
					// 	})
					// }

					if (this.autoOn === false) {
						let index =
							totalData.titles &&
							totalData.titles.findIndex((item) => {
								return item.key === "section"
							})
						console.log(index)
						totalData.titles.splice(index, 1)
					}
					return (tempTitles = totalData.titles)
				} else if (data && data.length > 0) {
					// for (let i = 0, len = data.length; i < len; i++) {
					tempTitles.push({
						title: "SKU",
						dataIndex: "SKU",
						key: "SKU",
					})
					let tempObj = lodash.omit({ ...data[0] }, [
						"定价",
						"section",
						"SKU",
						"id", // id 是不需要需要在titles中传给后端的
					])
					for (let key in tempObj) {
						tempTitles.push({
							title: key,
							dataIndex: key,
							key: key,
						})
					}

					tempTitles.push({
						title: "单件定价(元)",
						dataIndex: "定价",
						key: "定价",
						scopedSlots: {
							customRender: "定价",
						},
					})

					if (this.autoOn === true) {
						tempTitles.push({
							title: "批量设定",
							// dataIndex: "section",
							// key: "section",
							scopedSlots: {
								customRender: "section",
							},
						})
					}

					console.log(tempTitles)
					return tempTitles
				}
			},
			// 点击提交后 排序得到的数据
			async getTotalData(totalData, option1, option2) {
				console.log(totalData, option1, option2)
				console.log(totalData, this.data, this.changePFlag)
				if (this.changePFlag) {
					// 如果价格修改过 再提交

					// 解决 修改价格后点提交 价格没了 的问题
					if (this.data) {
						// data是页面上表格显示的数据
						// if (totalData.titles.length > 0) {
						// 	totalData.titles = [...totalData.titles]
						// } else {
						// }

						// totalData.titles = [...totalData.titles]

						totalData.titles = this.handleTitles_1(totalData, this.data)

						totalData.values = this.data

						console.log(totalData)
					}

					this.changePFlag = false
				} else {
					// 如果价格没修改过 直接提交
					if (this.data) {
						// data是页面上表格显示的数据
						// totalData.titles = [...totalData.titles]
						totalData.titles = this.handleTitles_1(totalData, this.data)
						totalData.values = this.data.map((item) => {
							console.log(item["定价"])
							item["定价"] = item["定价"] ? Math.round(item["定价"] * 100) : ""
							return item
						})

						console.log(totalData)
					}
				}

				if (
					totalData.values.some((item) => {
						return !(item["定价"] + "")
					})
				) {
					return this.$message.warning({
						duration: 3,
						content: "sku表中定价必须填满",
					})
				}
				// if (totalData.titles.length === 0 && totalData.values.length === 0) {
				// 	// 没做任何操作 直接点保存  => {titles: [], values: []}
				// 	console.log(this.option3)
				// 	totalData = this.option3 // 赋值网络返回数据
				// }
				if (!totalData) {
					// 没提交时 赋值网络返回数据
					totalData = this.option3
				}

				console.log(totalData)
				// // 页面展示
				// this.columns = totalData.titles
				// this.data = totalData.values
				// 重新渲染定价表 修复提交后 价格不更新问题
				this.flag = false
				setTimeout(() => {
					this.flag = true
				})

				// ====================================
				console.log("option3", totalData)
				// 修改价格时 提交到后端数据
				this.option3 = totalData

				console.log(this.getMarketId, this.getPtype)

				option2["unit"] = this.unit ? this.unit : "件" // 给批量设定添加单位

				if (this.autoOn === false) {
					// option2 = {}
					for (let i = 0, len = totalData.values.length; i < len; i++) {
						if (Object.keys(totalData.values[i]).includes("section")) {
							delete totalData.values[i].section
						}
					}
				}

				let params = {
					market_id: this.getMarketId,
					ptype: this.getPtype,
					option1: JSON.stringify(option1),
					option2: JSON.stringify(option2),
					option3: JSON.stringify(totalData),
				}
				console.log(params)
				// return;
				await marketHttp
					// .update(this.getProductId, params, "/skuproduct")
					.update(this.$route.params.id, params, "/skuproduct")
					.then((response) => {
						console.log(response)
						if (response.code !== 1) {
							this.$message.error(response.message)
							return
						}
						// 提交完成后再次获取商品详情
						this.getProductDetail_()
						return
					})
					.catch((e) => {
						console.log(e)
					})

				// if(totalData.length > 0){
				// 	this.columns = []
				// 	totalData.map(item => {

				// 	})
				// }
			},

			switchChecked(checked) {
				// this.check = checked
				if (checked === true) {
					this.addBatchSet()
				} else {
					this.removeBatchSet()
				}
				// this.columns = this.columns
			},
			handleTableChange(pagination, filters, sorter) {
				console.log(pagination.current, pagination.pageSize)
				this.pagination.current = pagination.current
				this.pagination.pageSize = pagination.pageSize
			},
			// addAttr() {
			// 	// this.$refs.handleTable.showModal("add")
			// },
			backPrice() {
				// this.$emit("changeFalse", false)
				// this.setPriceTableStatus(false)
				this.$router.back()
			},
		},
		components: {
			handleTable,
			EditableCell,
		},
	}
</script>

<style scoped lang='less'>
	.price-table {
		position: relative;
		padding-bottom: 60px;
		min-height: calc(100vh - 117px);
		.submit-btn {
			position: absolute;
			right: 20px;
			bottom: 15px;
		}
	}
</style>